var currentStatus="all";
var domainIp="localhost";   //配置服务器部署ip
var port = "8779"
// var domainIp="localhost";   //配置服务器部署ip
$(document).ready(function () {
    layui.use('element',function () {
        var element=layui.element;
    });
    console.log(domainIp);
    // console.log(window.screen.width);
    // console.log(window.screen.height);
    //
    // console.log(document.body.offsetWidth);
    // console.log(document.body.clientHeight);
    showTaskInit();

});

function showTaskInit() {
    // applyActionToHelpLink();
    generateAllPlaceTable("all");
    $("#routePlanTab").on('click',function () {
        routePlanInit();
    });
    $("#goToRoutePlanBtn").on('click',function () {
        $("#routePlanTab").trigger("click");
    });

    //给过滤单选radio和搜索框增加监听
    radioAndSearchBoxFilter();
}


//给单选过滤器和搜索过滤器增加监听
function radioAndSearchBoxFilter(){
    //搜索框
    $("#filterSearchBtn").on("click",function (event) {
        console.log($("#filterSearchBox").val());
        resetRadios();
        //判断发生改变后inputValue是否为空
        //为空则产生全部节点
        if ($("#filterSearchBox").val()===""){
            generateAllPlaceTable("all");
        }
        //为其他则调用搜索框
        else{
            generateAllPlaceTable_searchBox($("#filterSearchBox").val());
        }
    });

    //单选过滤器
    layui.use(['form'],function(){
        var form=layui.form;
        //用于记录当前filter状态
        currentStatus=form.val("filterForm")["filterRadio"];    //获取当前filter的值
        form.on('radio(filter-radio)',function (data) {
            // console.log(data.elem);
            // console.log(data.value);
            //判断是否已经选中这个过滤器
            //此时根据过滤器刷新table
            if(currentStatus!==data.value){
                console.log("changed to the filter type: "+data.value);
                currentStatus=data.value;
                //清空搜索框
                $("#filterSearchBox").val("");
                generateAllPlaceTable(data.value);
            }
        });
    });

}

//重置单选过滤器
function resetRadios(){
    layui.use('form',function () {
        var form=layui.form;
        form.val('filterForm',{
            "filterRadio":"all"
        });
    });
    currentStatus="all";

}

//给帮助链接增加监听
function applyActionToHelpLink() {
    $("#allNodeTips a:eq(0)").on('click',function () {
        layer.open({
            title:'Tips',
            id:'attributeTips_layer',
            btn:['okay'],
            content:
                '<div>' +
                '   <cite>Longitude and Latitude</cite> specify the detailed location of task places' +
                '</div>' +
                '<div>' +
                '   <cite>Time Limit</cite> gives the time limit of each task' +
                '</div>' +
                '<div>' +
                '   <cite>Payment</cite> gives the payment that is obtained from the task' +
                '</div>' +
                '<div>' +
                '   <cite>Priority</cite> gives the classification of each task place: ' +
                '   <cite>0</cite> for unaccessable places; ' +
                '   <cite>1</cite> for optional places; ' +
                '   <cite>2</cite> for obligatory places' +
                '</div>'
        })
    })
}

/**
 * 非搜索框生成表格
 * @param filterMode   "all" "obligatory" "selectable" "forbidden"
 */
function generateAllPlaceTable(filterMode) {
    layui.use(['table', 'form', 'layer'], function () {
        var table = layui.table;

        //两种模式渲染表格
        table.render({
            elem: '#placeTable'
            // , url: 'http://localhost:8779/edge/queryPlacesByFilterForm'
            , url: 'http://'+domainIp + ':' + port + '/task-assign/single-route-plan/queryPlacesByFilterForm'
            ,where:{
                filterMode:filterMode
            }
            , toolbar: '#topBarTool'
            , title: '用户数据表'
            , cols: [[
                {field: 'id', title: 'ID', align: "center", sort: true}
                ,{field:'taskName',title:'名称',align:'center',edit:'text'}
                , {field: 'jing', title: '经度', align: "center", edit: 'text'}
                , {field: 'wei', title: '纬度', align: "center", edit: 'text'}
                , {field: 'time', title: '时间窗', align: "center",  edit: 'text',templet:function (d) {
                        return transferSecondToTime(d.time);
                    }}
                , {field: 'earn', title: '收益', align: "center", sort: true, edit: 'text'}
                , {field: 'pri', title: '优先级', align: "center", sort: true,edit:'text' ,templet: function (d) {
                        if(d.pri===2){
                            return '<span style="color: red">'+d.pri+'</span>'
                        }
                        else if(d.pri===1){
                            return '<span style="color: black">'+d.pri+'</span>'
                        }
                        else if(d.pri===0){
                            return '<span style="color: lightgrey">'+d.pri+'</span>'
                        }
                    }}
                , {title:'Operation',align: 'center', toolbar: '#lineBarTool'}
            ]]
            
            , page: true //开启分页
            ,limit:10
            ,limits:[5,10,15,20]
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , groups: 1 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
        });

        // //开启分页
        // laypage.render({
        //     elem:'placeTable',
        //     count:15,
        //     limit:5,
        //     limits:[5,10,15],
        //     groups:1,
        //     layout:['limit', 'count', 'prev', 'page', 'next', 'skip'],
        //     first:false,
        //     last:false
        // });


        //监听头部工具栏
        table.on('toolbar(placeTable)', function (obj) {
            // var checkStatus = table.checkStatus(obj.config.id);
            if (obj.event === 'addTaskEvent') {
                addTaskLayer();
            }
        });
        //监听尾部工具栏
        table.on('tool(placeTable)', function (obj) {
            var id = obj.data.id;
            if (obj.event === 'del') {
                layer.confirm('确认删除节点？',
                    {
                        title:'Message',
                        btn:['yes','no']
                    },
                    function (index) {
                    // console.info(id);
                    $.ajax({
                        type: 'POST',
                        // url: 'http://localhost:8779/edge/deleteTaskById',
                        url:'http://'+domainIp+':' + port + '/task-assign/single-route-plan/deleteTaskById',
                        data: {id: id}, //前面是controller变量 后面是js中var
                        // async: false,
                        success: function (info) {
                            if(info.code===200){
                                obj.del();
                                layer.msg(info.msg);
                                layer.close(index);
                            }
                            else{
                                exceptionLayer(info.msg);
                            }
                        },
                        error: function (errorInfo) {
                            exceptionLayer(errorInfo.responseText);
                        }
                    });
                });
            }
        });

        //监听单元格编辑
        table.on('edit(placeTable)', function (obj) {
            console.log(obj);
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            var check = true;   //判断输入有效性
            var regInt = /^\d+$/;
            var regFloat = /^\d+\.\d{1,3}$/;
            var regPri=/^(0|1|2)$/;
            switch (field) {
                case 'jing': {
                    if (regInt.test(value) === false && regFloat.test(value) === false) {
                        check = false;
                        layer.open({
                           title:'消息',
                           content:  '经度必须是整数或者三位及以内小数'
                        });

                    }
                }
                    break;
                case 'wei': {
                    if (regInt.test(value) === false && regFloat.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'消息',
                            content:'纬度必须是整数或者三位及以内小数'
                        });

                    }
                }
                    break;
                case 'time': {
                    if (regInt.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'消息',
                            content:'时限必须是整数'
                        });
                    }
                }
                    break;
                case 'earn': {
                    if (regInt.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'消息',
                            content:'收益必须是整数'
                        });
                    }
                }
                    break;
                case 'pri': {
                    if (regPri.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'消息',
                            content:'优先级只可以是0，1或2'
                        });
                    }
                }
                    break;
                default:
                    break;
            }
            if (check === true) {
                $.ajax({
                    type: 'POST',
                    // url: 'http://localhost:8779/edge/reset',
                    url: 'http://'+domainIp+':' + port + '/task-assign/single-route-plan/reset',
                    data: {
                        id: data.id,
                        wei: data.wei,
                        jing: data.jing,
                        time: data.time,
                        earn: data.earn,
                        pri: data.pri,
                        taskName:data.taskName,
                        carid:0
                    }, //前面是controller变量 后面是js中var
                    async: false,
                    success: function (info) {
                        if (info.code===200){
                            layer.msg(info.msg);
                            generateAllPlaceTable(currentStatus);
                        }
                        else{
                            exceptionLayer(info.msg);
                        }

                    },
                    error: function (errorInfo) {
                        // layer.alert(errorInfo.responseText,{
                        //     title:'Message',btn:'okay'
                        // });
                        exceptionLayer(errorInfo.responseText);
                    }
                });
            } else {
                //局部刷新表格
                generateAllPlaceTable(currentStatus);
            }
        });
    });
}

/**
 * 非搜索框生成表格
 * @param inputValue   "..."
 */
function generateAllPlaceTable_searchBox(inputValue) {
    layui.use(['table', 'form', 'layer'], function () {
        var table = layui.table;
        //渲染表格
        table.render({
            elem: '#placeTable'
            // , url: 'http://localhost:8779/edge/queryPlacesBySearchBox'
            , url: 'http://'+domainIp+':' + port + '/task-assign/single-route-plan/queryPlacesBySearchBox'
            ,where:{
                inputValue:inputValue
            }
            , toolbar: '#topBarTool'
            , title: '用户数据表'
            , cols: [[
                {field: 'id', title: 'ID', align: "center", sort: true}
                ,{field:'taskName',title:'名称',align:'center',edit:'text'}
                , {field: 'jing', title: '经度', align: "center", edit: 'text'}
                , {field: 'wei', title: '纬度', align: "center", edit: 'text'}
                , {field: 'time', title: '时间窗', align: "center",  edit: 'text',templet:function (d) {
                        return transferSecondToTime(d.time);
                    }}
                , {field: 'earn', title: '收益', align: "center", sort: true, edit: 'text'}
                , {field: 'pri', title: '优先级', align: "center", sort: true,edit:'text' ,templet: function (d) {
                        if(d.pri===2){
                            return '<span style="color: red">'+d.pri+'</span>'
                        }
                        else if(d.pri===1){
                            return '<span style="color: black">'+d.pri+'</span>'
                        }
                        else if(d.pri===0){
                            return '<span style="color: lightgrey">'+d.pri+'</span>'
                        }
                    }}
                , {title:'Operation',align: 'center', toolbar: '#lineBarTool'}
            ]]
            , page: true //开启分页
            , limit: 10
            , limits: [5, 10, 15,20]
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , groups: 1 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
            }
        });

        //监听头部工具栏
        table.on('toolbar(placeTable)', function (obj) {
            // var checkStatus = table.checkStatus(obj.config.id);
            if (obj.event === 'addTaskEvent') {
                addTaskLayer();
            }
        });
        //监听尾部工具栏
        table.on('tool(placeTable)', function (obj) {
            var id = obj.data.id;
            if (obj.event === 'del') {
                layer.confirm('Are you sure to delete the place?',
                    {
                        title:'Message',
                        btn:['yes','no']
                    },
                    function (index) {
                        // console.info(id);
                        $.ajax({
                            type: 'POST',
                            // url: 'http://localhost:8779/edge/deleteTaskById',
                            url: 'http://'+domainIp+':' + port + '/task-assign/single-route-plan/deleteTaskById',
                            data: {id: id}, //前面是controller变量 后面是js中var
                            async: false,
                            success: function (info) {
                                if (info.code===200){
                                    obj.del();
                                    layer.msg(info.msg);
                                    layer.close(index);
                                }
                                else{
                                    // layer.alert(info.msg,{
                                    //     title:'Message',btn:'okay'
                                    // });
                                    exceptionLayer(info.msg);
                                }

                            },
                            error: function (errorInfo) {
                                // layer.alert(errorInfo.responseText,{
                                //     title:'Message',btn:'okay'
                                // });
                                exceptionLayer(errorInfo.responseText);
                            }
                        });
                    });
            }
        });

        //监听单元格编辑
        table.on('edit(placeTable)', function (obj) {
            console.log(obj);
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            var check = true;   //判断输入有效性
            var regInt = /^\d+$/;
            var regFloat = /^\d+\.\d{1,3}$/;
            var regPri=/^(0|1|2)$/
            switch (field) {
                case 'jing': {
                    if (regInt.test(value) === false && regFloat.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'Message',
                            content:  '经度必须是整数或者三位及以内小数'
                        });
                    }
                }
                    break;
                case 'wei': {
                    if (regInt.test(value) === false && regFloat.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'Message',
                            content:'纬度必须是整数或者三位及以内小数'
                        });
                    }
                }
                    break;
                case 'time': {
                    if (regInt.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'Message',
                            content:'时限必须是整数'
                        });
                    }
                }
                    break;
                case 'earn': {
                    if (regInt.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'Message',
                            content:'收益必须是整数'
                        });
                    }
                }
                    break;
                case 'pri': {
                    if (regPri.test(value) === false) {
                        check = false;
                        layer.open({
                            title:'Message',
                            content:'优先级只可以是0，1，2'
                        });
                    }
                }
                    break;
                default:
                    break;
            }
            if (check === true) {
                $.ajax({
                    type: 'POST',
                    // url: 'http://localhost:8779/edge/reset',
                    url: 'http://'+domainIp+':' + port + '/task-assign/single-route-plan/reset',
                    data: {
                        id: data.id,
                        wei: data.wei,
                        jing: data.jing,
                        time: data.time,
                        earn: data.earn,
                        pri: data.pri,
                        taskName:data.taskName,
                        carid:0
                    }, //前面是controller变量 后面是js中var
                    async: false,
                    success: function (info) {
                        if (info.code===200){
                            layer.msg(info.msg);
                            generateAllPlaceTable_searchBox(inputValue);
                        }
                        else{
                            // layer.alert(info.msg,{
                            //     title:'Message',btn:'okay'
                            // });
                            exceptionLayer(info.msg);
                        }

                    },
                    error: function (errorInfo) {
                        // layer.alert(errorInfo.responseText,{
                        //     title:'Message',btn:'okay'
                        // });
                        exceptionLayer(errorInfo.responseText);
                    }
                });
            } else {
                //局部刷新表格
                generateAllPlaceTable_searchBox(inputValue);
            }
        });
    });
}

//添加任务的弹窗
function addTaskLayer(){
    layui.use(['table', 'form', 'layer', 'jquery'], function () {
        var table = layui.table, layer = layui.layer, form = layui.form, $ = layui.jquery;
        var that = this;
        layer.open({
            type: 1,  //1公告，2iframe
            title: false, //弹窗标题
            closeBtn: false,
            // area: [(0.36*(window.screen.width))+'px', (0.343*(window.screen.height))+'px'],
            area:['680px','380px'],
            shade: 0.8,
            id: 'addTask_layer', //设定一个id，防止重复弹出
            // btn:['添加','取消'],
            // btnAlign: 'c',//文字居中
            moveType: 1, //拖拽模式，0或者1
            content:
                '    <fieldset id="addTaskTitle_layer" class="layui-elem-field layui-field-title">' +
                '        <legend>添加一个任务</legend>' +
                '    </fieldset>' +
                '<!--    方框风格表格-->' +
                '    <form id="addTaskForm_layer" class="layui-form layui-form-pane">' +
                '        <div class="layui-form-item">' +
                '            <label class="layui-form-label">任务名称</label>' +
                '            <div class="layui-input-block">' +
                '                <input type="text" name="taskName" lay-verify="required" autocomplete="off" placeholder="请输入任务名称" class="layui-input">' +
                '            </div>' +
                '        </div>' +
                '        <div class="layui-form-item">' +
                '            <div class="layui-inline">' +
                '                <label class="layui-form-label">经度</label>' +
                '                <div class="layui-input-block">' +
                '                    <input type="text" name="jing" lay-verify="required|jing" placeholder="请输入经度" autocomplete="off" class="layui-input">' +
                '                </div>' +
                '            </div>' +
                '            <div class="layui-inline">' +
                '                <label class="layui-form-label">纬度</label>' +
                '                <div class="layui-input-block">' +
                '                    <input type="text" name="wei" lay-verify="required|wei" placeholder="请输入纬度" autocomplete="off" class="layui-input">' +
                '                </div>' +
                '            </div>' +
                '        </div>' +
                '        <div class="layui-form-item">' +
                '            <div class="layui-form-label">优先级</div>' +
                '            <div class="layui-input-block">' +
                '                <input type="text" name="priority" lay-verify="required|priority" placeholder="请输入优先级" autocomplete="off" class="layui-input">' +
                '            </div>' +
                '        </div>' +
                '' +
                '        <div class="layui-form-item">' +
                '            <div class="layui-inline">' +
                '                <div class="layui-form-label">收益</div>' +
                '                <div class="layui-input-block">' +
                '                    <input type="text" name="pay" lay-verify="required|pay" placeholder="请输入任务收益" autocomplete="off" class="layui-input">' +
                '                </div>' +
                '            </div>' +
                '            <div class="layui-inline">' +
                '            <div class="layui-form-label">时间窗</div>' +
                '            <div class="layui-input-block">' +
                '                <input type="text" name="timeWindow" lay-verify="required|timeWindow" placeholder="请输入时间限制" autocomplete="off" class="layui-input">' +
                '            </div>' +
                '        </div>' +
                '        </div>' +
                // '        <div class="layui-form-item">' +
                // '            <div class="layui-input-block">' +
                // '                <button class="layui-btn" lay-submit="" lay-filter="submitAdd">Add Task</button>' +
                // '                <button type="reset" class="layui-btn layui-btn-primary">Reset Form</button>' +
                // '                <button type="reset" class="layui-btn layui-btn-danger" id="cancelAddBtn">Cancel</button>' +
                // '            </div>' +
                // '        </div>' +
                '        <div class="layui-fluid">' +
                '           <div class="layui-row">' +
                '               <div class="layui-col-sm4">' +
                '                   <div class="addTaskBtnGroup1"><button class="layui-btn" lay-submit="" lay-filter="submitAdd">添加任务</button></div>' +
                '               </div>' +
                '               <div class="layui-col-sm4">' +
                '                   <div class="addTaskBtnGroup2"><button type="reset" class="layui-btn layui-btn-primary">重置表单</button></div>' +
                '               </div>' +
                '               <div class="layui-col-sm4">' +
                '                   <div class="addTaskBtnGroup3"><button type="reset" class="layui-btn layui-btn-danger" id="cancelAddBtn">取消并退出</button></div>' +
                '               </div>' +
                '           </div>' +
                '        </div>' +
                '    </form>'
        });
        //自适应屏幕宽度
        // var inlineWidth_layer=$("#addTask_layer").offset().width;
        var inlineWidth_layer=document.getElementById("addTask_layer").offsetWidth;
        console.log("弹出层宽度"+inlineWidth_layer);
        $("#addTask_layer .layui-inline").css("width",0.4*inlineWidth_layer+"px");

        //自定义验证规则
        form.verify({
            required:function(value){
              if(value===""||value===null){
                  return '不可以输入空值';
              }
            },
            jing: function (value) {
                var regInt = /^\d+$/;
                var regFloat = /^\d+\.\d{1,3}$/;
                if (regInt.test(value) === false && regFloat.test(value) === false) {
                    return '经度必须是整数或者三位及以内小数';
                }
            },
            wei: function (value, item) {
                var regInt = /^\d+$/;
                var regFloat = /^\d+\.\d{1,3}$/;
                if (regInt.test(value) === false && regFloat.test(value) === false) {
                    return '纬度必须是整数或者三位及以内小数';
                }
            },
            priority: function (value, item) {
                var regPri=/^(0|1|2)$/;
                if (regPri.test(value)===false) {
                    return '优先级只可以是0，1或2';
                }
            },
            pay: function (value, item) {
                var regInt = /^\d+$/;
                if (regInt.test(value) === false) {
                    return '收益必须是整数';
                }
            },
            timeWindow: function (value, item) {
                var regInt = /^\d+$/;
                if (regInt.test(value) === false) {
                    return '时限必须是整数';
                }
            },
        });
        //监听取消按钮
        $('#cancelAddBtn').on('click', function () {
            layer.closeAll();
        });
        //监听提交
        form.on('submit(submitAdd)', function (formData) {
            layer.confirm('确认添加任务？', {title:'消息',btn:['是','否']},function () {
                $.ajax({
                    type: "post",
                    // url: "http://localhost:8779/edge/addTask",
                    url: "http://"+domainIp+':' + port + '/task-assign/single-route-plan/addTask',
                    data: {
                        jing: formData.field.jing,
                        wei: formData.field.wei,
                        pri: formData.field.priority,
                        earn: formData.field.pay,
                        time: formData.field.timeWindow,
                        taskName: formData.field.taskName
                    },
                    dataType: "json",
                    success: function (info) {
                        if (info.code===200){
                            generateAllPlaceTable("all");
                            resetRadios();
                            layer.closeAll();
                            layer.msg(info.msg);
                        }
                        else{
                            // layer.alert(info.msg,{
                            //     title:'Message',btn:'okay'
                            // });
                            exceptionLayer(info.msg);
                        }

                    },
                    error:function (errorInfo) {
                        // layer.alert(errorInfo.responseText,{
                        //     title:'Message',btn:'okay'
                        // });
                        exceptionLayer(errorInfo.responseText);
                    }

                });
                console.log(formData.field);
                // layer.closeAll();
            });
            return false;
        });
    });

}


function exceptionLayer(errorMsg){
    layer.alert(errorMsg,{
        title:'Message',btn:'okay'
    })
}


